﻿using System;
using UFIDA.U9.BS.SiteKeyProviders;
using UFIDA.UBF.SystemManage;
using UFSoft.UBF.Engine;
using UFSoft.UBF.Service;
using UFSoft.UBF.Util.Context;

namespace UFSoft.UBF.Cust.ClassView.MVC.Proxy
{
    public class WSSPortalSiteKeyProvider : IDirectoryProvicder, IAppInfoProvider, IServiceCheckProvider
    {
        public const string DisableCheckOneProxyEnabledSymbol = "__WSS_DisableCheckOneProxyEnabled";
        private static readonly object LockObject = new object();

        public WSSPortalSiteKeyProvider(PortalSiteKeyProvider provider)
        {
            if (provider == null)
                throw new ArgumentException("PortalSiteKeyProvider is null");
            Provider = provider;
        }

        public PortalSiteKeyProvider Provider { get; }

        public void InitBPMap()
        {
            Provider.InitBPMap();
        }

        public void UpdateAppStateCache()
        {
            Provider.UpdateAppStateCache();
        }

        public SvcEndpoint GetAddress(string srvName, Token token)
        {
            return Provider.GetAddress(srvName, token);
        }

        public bool IsServiceEnabled(string bpName, Token token, out string errorMsg)
        {
            if (PlatformContext.Current == null ||
                PlatformContext.Current[DisableCheckOneProxyEnabledSymbol] == null ||
                PlatformContext.Current[DisableCheckOneProxyEnabledSymbol].ToString() !=
                true.ToString())
                return Provider.IsServiceEnabled(bpName, token, out errorMsg);
            //只使用一次
            PlatformContext.Current[DisableCheckOneProxyEnabledSymbol] = null;
            errorMsg = string.Empty;
            return true;
        }

        public bool IsTargetOrgUserEnabled(long targetOrgID)
        {
            return Provider.IsTargetOrgUserEnabled(targetOrgID);
        }

        /// <summary>
        ///     替换服务校验服务
        /// </summary>
        public static void ReplaceServiceCheckProvider()
        {
            lock (LockObject)
            {
                //重新注册服务校验服务
                IServiceCheckProvider provider = ServiceProvider.Instance.GetService<IServiceCheckProvider>();
                if (!(provider is PortalSiteKeyProvider)) return;
                ServiceProvider.Instance.RemoveService(provider);
                ServiceProvider.Instance.AddService(new WSSPortalSiteKeyProvider(provider as PortalSiteKeyProvider));
            }
        }

        /// <summary>
        ///     禁止检查下一个代理有效
        ///     代理类调用前调用这个方法
        /// </summary>
        public static void DisableCheckOneProxy()
        {
            using (new SystemWritablePolicy())
            {
                PlatformContext.Current[DisableCheckOneProxyEnabledSymbol] = true;
            }
        }
    }
}